import { Injectable, HttpException } from '@nestjs/common';
import { PrismaService } from '../prisma.service';
import { Prisma } from '@prisma/client';

@Injectable()
export class RoleService {
    constructor(private prisma: PrismaService) { }

    // 创建角色
    async create(data: Prisma.RoleCreateInput) {
        const existRole = await this.prisma.role.findFirst({
            where: {
                OR: [
                    { roleName: data.roleName },
                    { roleKey: data.roleKey }
                ]
            }
        });

        if (existRole) {
            throw new HttpException('角色名称或标识已存在', 400);
        }

        return this.prisma.role.create({ data });
    }

    // 更新角色
    async update(id: number, data: Prisma.RoleUpdateInput) {
        return this.prisma.role.update({
            where: { id },
            data
        });
    }

    // 删除角色
    async delete(id: number) {
        return this.prisma.role.delete({
            where: { id }
        });
    }

    // 获取角色列表
    async findAll(params: {
        skip?: number;
        take?: number;
        where?: Prisma.RoleWhereInput;
        orderBy?: Prisma.RoleOrderByWithRelationInput;
    }) {
        const { skip, take, where, orderBy } = params;
        const [total, items] = await Promise.all([
            this.prisma.role.count({ where }),
            this.prisma.role.findMany({
                skip,
                take,
                where,
                orderBy,
                include: {
                    roleMenus: {
                        include: {
                            menu: true
                        }
                    }
                }
            })
        ]);

        return {
            items,
            total
        };
    }

    // 获取角色详情
    async findOne(id: number) {
        return this.prisma.role.findUnique({
            where: { id },
            include: {
                roleMenus: {
                    include: {
                        menu: true
                    }
                }
            }
        });
    }

    // 更新角色菜单
    async updateRoleMenus(roleId: number, menuIds: number[]) {
        // 先删除原有菜单
        await this.prisma.roleMenu.deleteMany({
            where: { roleId }
        });

        // 添加新菜单
        const roleMenus = menuIds.map(menuId => ({
            roleId,
            menuId
        }));

        await this.prisma.roleMenu.createMany({
            data: roleMenus
        });

        return this.findOne(roleId);
    }
} 